package com.tang.gateway.filter;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.tang.common.enums.HeaderAndContextNameEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 登录拦截器
 *
 * @author Tang
 * @date 2024/2/20 18:06
 **/
@Slf4j
@Component
public class LoginFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        log.info("com.tang.gateway.filter.LoginFilter.filter.url:{}", path);
        //放行登录接口
        if (StringUtils.equals(path, "/user/doLogin") || StringUtils.equals(path, "/user/getUserInfo")) {
            return chain.filter(exchange);
        }
        //获取用户唯一标识
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        String loginId = tokenInfo.getLoginId().toString();
        //增加请求头
        ServerHttpRequest.Builder mutate = request.mutate();
        mutate.header(HeaderAndContextNameEnum.LOGIN_ID.getName(), loginId);
        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }
}
